'use strict';

const Service = require('egg').Service;

class ViewService extends Service {
  async getList() {
    const {
      ctx,
      app
    } = this;
    const {
      pageSize,
      pageIndex,
      ip,
      userAgent,
      url,
      count,
      address,
      browser,
      engine,
      os,
      device
    } = ctx.query;
    let sql = `select * from view where 1=1 `;
    let countSql = `select count(id) as total from view where 1=1 `
    if (ip) {
      sql += `and ip="${ip}" `
      countSql += `and ip="${ip}" `
    }
    if (userAgent) {
      sql += `and userAgent="${userAgent}" `
      countSql += `and userAgent="${userAgent}" `
    }
    if (url) {
      sql += `and url="${url}" `
      countSql += `and url="${url}" `
    }
    if (count) {
      sql += `and count="${count}" `
      countSql += `and count="${count}" `
    }
    if (address) {
      sql += `and address="${address}" `
      countSql += `and address="${address}" `
    }
    if (browser) {
      sql += `and browser like "%${browser}%" `
      countSql += `and browser like "%${browser}%" `
    }
    if (engine) {
      sql += `and engine="${engine}" `
      countSql += `and engine="${engine}" `
    }
    if (os) {
      sql += `and os like "%${os}%" `
      countSql += `and os like "%${os}%" `
    }
    if (device) {
      sql += `and device like "%${device}%" `
      countSql += `and device like "%${device}%" `
    }
    if (pageSize && pageIndex) {
      sql += `limit ${(pageIndex-1)*pageSize},${pageSize} `
    }
    const res = await app.mysql.query(sql);
    const [{
      total
    }] = await app.mysql.query(countSql);
    return {
      data: res,
      total,
    }
  }
  async delView() {
    const {
      ctx,
      app
    } = this;

    const {
      id
    } = ctx.request.body;
    console.log(id);
    const res = await app.mysql.delete('view', {
      id
    });
    return res
  }
  async delViews() {
    const {
      ctx,
      app
    } = this;

    const {
      selection
    } = ctx.request.body;
    let res = null;
    await selection.forEach((item) => {
      res = app.mysql.delete('view', {
        id: item.id
      });
    })
    return res
  }
}

module.exports = ViewService;